package com.hunttown.mes.manage.controller._erp;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.rpc.domain.*;
import com.hunttown.mes.rpc.domain.enums.purchase.ProductTypeEnum;
import com.hunttown.mes.rpc.domain.enums.purchase.OutRuleTypeEnum;
import com.hunttown.mes.rpc.domain.enums.purchase.PurchaseCateEnum;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.*;
import com.hunttown.mes.manage.service.*;
import com.hunttown.mes.rpc.domain.query.TransportPurchaseDTOQuery;
import com.hunttown.mes.rpc.domain.query.TransportPurchaseDetailDTOQuery;
import com.hunttown.mes.rpc.domain.query.TransportPurchaseInventoryDetailDTOQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * @title: 采销管理
 * @author: wangjunfu
 * @date: 2019-05-25 10:36:38
 * @description:
 */
@Controller
@RequestMapping(value = "/erp/purchase")
public class PurchaseController {

    private final static Logger logger = LoggerFactory.getLogger(PurchaseController.class);

    private final TransportPurchaseManageService purchaseService;
    private final AnalysisManageManageService manageService;
    private final ModelService modelService;
    private final TransportPurchaseDetailManageService purchaseDetailService;
    private final TransportPurchaseInventoryDetailManageService inventoryDetailService;
    private final TransportPurchaseInventoryManageService inventoryService;
    private final TransportOperateLogManageService logService;

    @Autowired
    public PurchaseController(TransportPurchaseManageService purchaseService, AnalysisManageManageService manageService, ModelService modelService, TransportPurchaseDetailManageService purchaseDetailService, TransportPurchaseInventoryDetailManageService inventoryDetailService, TransportPurchaseInventoryManageService inventoryService, TransportOperateLogManageService logService) {
        this.purchaseService = purchaseService;
        this.manageService = manageService;
        this.modelService = modelService;
        this.purchaseDetailService = purchaseDetailService;
        this.inventoryDetailService = inventoryDetailService;
        this.inventoryService = inventoryService;
        this.logService = logService;
    }

    //region 数据列表

    /**
     * 首页
     *
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return vm
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model, TransportPurchaseDTOQuery dtoQuery) {

        //已下架物料
        if (dtoQuery.getIsStop() == null || dtoQuery.getIsStop() == 0) {
            dtoQuery.setIsStop(0);
        } else {
            dtoQuery.setStopFlag(1);
        }

        dtoQuery.setOrderBy("order by stop_flag asc, id desc");
        Page<TransportPurchaseDTO> dataPage = purchaseService.getForPage(dtoQuery);

        //region 实时更新列表信息
        if (dataPage != null && dataPage.getItems().size() > 0) {
            List<Map<String, String>> rmapList;

            int year = DateUtils.getCurrYear();
            int month = DateUtils.getCurrMonth();

            //盘点单
            TransportPurchaseInventoryDTO inventoryDTO;

            //盘点明细
            TransportPurchaseInventoryDetailDTOQuery inventoryDetailQuery;
            TransportPurchaseInventoryDetailDTO inventoryDetailDTO;

            for (TransportPurchaseDTO item : dataPage.getItems()) {
                //适用车型
                item.setModelCn(modelService.getCatalogName(item.getModelId()));

                //类别名称
                item.setCatalogName(modelService.getCatalogName(item.getCatalogId()));

                //类型
                item.setGoodsTypeName(PurchaseCateEnum.getEnumByKey(item.getGoodsType()));

                //仓库
                item.setStorageName(modelService.getCatalogName(item.getStorage()));

                //品牌
                item.setBrandName(modelService.getCatalogName(item.getBrandId()));

                //出库规则
                item.setOutRuleName(OutRuleTypeEnum.getEnumByKey(item.getOutRule()));

                //库存信息
                rmapList = purchaseDetailService.selectSumCount(item.getId());
                if (rmapList != null) {
                    Map<String, String> rmap = rmapList.get(0);
                    Integer r_counts = GeneralUtils.ObjectToInt(rmap.get("r_counts"));
                    Integer c_counts = GeneralUtils.ObjectToInt(rmap.get("c_counts"));
                    Integer s_counts = GeneralUtils.ObjectToInt(rmap.get("s_counts"));

                    item.setInCount(r_counts);
                    item.setOutCount(c_counts);
                    item.setDamageCount(s_counts);
                    item.setStockCount(r_counts - c_counts - s_counts);
                }

                //盘点信息
                inventoryDetailQuery = new TransportPurchaseInventoryDetailDTOQuery();
                inventoryDetailQuery.setPartId(item.getId());
                inventoryDetailQuery.setpYear(year);
                inventoryDetailQuery.setpMonth(month);
                inventoryDetailDTO = inventoryDetailService.getByQuery(inventoryDetailQuery);

                //盘点信息：1本月未盘点 2本月已盘点、未审核 3本月已盘点、已审核
                if (inventoryDetailDTO == null) {
                    item.setInventoryInfo(1);
                } else {
                    inventoryDTO = inventoryService.getById(inventoryDetailDTO.getInventoryId());
                    if (inventoryDTO != null && inventoryDTO.getStatus() == 1) {
                        item.setInventoryInfo(3);
                    } else {
                        item.setInventoryInfo(2);
                    }
                }
            }
        }
        //endregion

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        if (dtoQuery.getPurchaseType() == 1) { //配件
            modelService.getCatalogPage(model, 17, "purchaseCate");
        }
        if (dtoQuery.getPurchaseType() == 2) { //采购
            modelService.getCatalogPage(model, 18, "purchaseCate");
        }

        //region 显示标题
        String showTitle = "未知";
        if (dtoQuery.getPurchaseType() == 1) {
            showTitle = "配件";
        }
        if (dtoQuery.getPurchaseType() == 2) { //采购
            showTitle = "物料";
        }
        model.addAttribute("showTitle", showTitle);
        //endregion

        //region 页面按钮权限
        String pin = AdminBaseClass.getPin(request);
        //编辑、删除、盘点、报销（配件和物料用的同一个页面）
        String[] menus = {"X-W-WLGL-BJ", "X-W-WLGL-QTY", "X-W-WLGL-SC", "X-W-WLPD-PD", "X-W-WLGL-PJMX",
                "Q-P-PJXX-BJ", "Q-P-PJXX-QTY", "Q-P-PJXX-SC", "Q-P-PJPD-PD", "Q-P-PJXX-PJMX",
                "C-B-PJBX-XZY", "C-B-CGBX-XZY"};
        model.addAttribute("Permission", manageService.GetBtnPermission(menus, pin));
        //endregion

        return "erp/purchase/index";
    }

    //详情
    @RequestMapping(value = "/getInfo", method = RequestMethod.POST)
    public String getInfo(Model model, Integer id) {

        //显示标题
        String showTitle = "未知";

        if (id != null && id > 0) {
            TransportPurchaseDTO obj = purchaseService.getById(id);

            if (obj != null) {
                //适用车型
                obj.setModelCn(modelService.getCatalogName(obj.getModelId()));

                //类别名称
                obj.setCatalogName(modelService.getCatalogName(obj.getCatalogId()));

                //类型
                obj.setGoodsTypeName(PurchaseCateEnum.getEnumByKey(obj.getGoodsType()));

                //仓库
                obj.setStorageName(modelService.getCatalogName(obj.getStorage()));

                //品牌
                obj.setBrandName(modelService.getCatalogName(obj.getBrandId()));

                //出库规则
                obj.setOutRuleName(OutRuleTypeEnum.getEnumByKey(obj.getOutRule()));

                //负责人
                obj.setChargeCn(modelService.getManageName(obj.getCharge()));

                //成品类型
                obj.setProductTypeName(ProductTypeEnum.getEnumByKey(obj.getProductType()));

                //库存信息
                List<Map<String, String>> rmapList = purchaseDetailService.selectSumCount(obj.getId());
                if (rmapList != null) {
                    Map<String, String> rmap = rmapList.get(0);
                    Integer r_counts = GeneralUtils.ObjectToInt(rmap.get("r_counts"));
                    Integer c_counts = GeneralUtils.ObjectToInt(rmap.get("c_counts"));
                    Integer s_counts = GeneralUtils.ObjectToInt(rmap.get("s_counts"));

                    obj.setInCount(r_counts);
                    obj.setOutCount(c_counts);
                    obj.setDamageCount(s_counts);
                    obj.setStockCount(r_counts - c_counts - s_counts);
                }

                int year = DateUtils.getCurrYear();
                int month = DateUtils.getCurrMonth();

                //盘点信息
                TransportPurchaseInventoryDetailDTOQuery inventoryDetailQuery = new TransportPurchaseInventoryDetailDTOQuery();
                inventoryDetailQuery.setPartId(obj.getId());
                inventoryDetailQuery.setpYear(year);
                inventoryDetailQuery.setpMonth(month);
                TransportPurchaseInventoryDetailDTO inventoryDetailDTO = inventoryDetailService.getByQuery(inventoryDetailQuery);

                //盘点信息：1本月未盘点 2本月已盘点、未审核 3本月已盘点、已审核
                if (inventoryDetailDTO == null) {
                    obj.setInventoryInfo(1);
                } else {
                    TransportPurchaseInventoryDTO inventoryDTO = inventoryService.getById(inventoryDetailDTO.getInventoryId());
                    if (inventoryDTO != null && inventoryDTO.getStatus() == 1) {
                        obj.setInventoryInfo(3);
                    } else {
                        obj.setInventoryInfo(2);
                    }
                }

                if (obj.getPurchaseType() == 1) {
                    showTitle = "配件";
                }
                if (obj.getPurchaseType() == 2) {
                    showTitle = "物料";
                }
            }

            model.addAttribute("purchaseObj", obj);
            model.addAttribute("showTitle", showTitle);
        }

        return "erp/purchase/purchase-detail-modal";
    }
    //endregion

    //region 编辑&保存

    /**
     * 编辑
     *
     * @param model model模型
     * @param id    主键id
     * @return vm
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(HttpServletRequest request, Model model, Integer id, Integer purchaseType) {
        id = (id == null ? 0 : id);

        TransportPurchaseDTO obj;

        if (id > 0) {
            obj = purchaseService.getById(id);
        } else {
            obj = new TransportPurchaseDTO();
            obj.setId(id);

            //设置默认值
            obj.setGoodsType(2);    //耗材
            obj.setWarningHigh(0);
            obj.setWarningLow(0);
            obj.setIsImport(0);
            obj.setUnit("件");
            obj.setKeepDay(0);
            obj.setProductType(2);

            //默认配件负责人
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            obj.setCharge(curr_obj.getId());
        }

        model.addAttribute("Obj", obj);
        model.addAttribute("purchaseType", purchaseType);

        modelService.getManagerPage(model);
        modelService.getCatalogPage(model, 9, "modelList");
        modelService.getCatalogPage(model, 20, "storageList");
        model.addAttribute("outRuleList", OutRuleTypeEnum.getEnumList());
        model.addAttribute("productTypeList", ProductTypeEnum.getEnumList());

        if (purchaseType == 1) {
            modelService.getCatalogPage(model, 6);  //配件品牌
            modelService.getCatalogPage(model, 17, "purchaseCate");
        }
        if (purchaseType == 2) {
            modelService.getCatalogPage(model, 21); //采购品牌
            modelService.getCatalogPage(model, 18, "purchaseCate");
        }

        //region 显示标题
        String showTitle = "未知";
        if (purchaseType == 1) {
            showTitle = "配件";
        }
        if (purchaseType == 2) {
            showTitle = "物料";
        }
        model.addAttribute("showTitle", showTitle);
        //endregion

        return "erp/purchase/edit";
    }

    /**
     * 保存 ajax异步
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return json
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, TransportPurchaseDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            if (objDTO.getStopFlag() == null) {
                objDTO.setStopFlag(0);
            }

            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                //设置初始值
                objDTO.setAdminId(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setDeleteFlag(0);
                //默认值
                objDTO.setCount(0);
                objDTO.setFrozenCount(0);
                objDTO.setSupplyId(0);

                objDTO = purchaseService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

            } else {
                //更新
                //将不需要更新的字段设置为NULL
                Boolean isNext = purchaseService.updateInfoById(objDTO);
                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //region *** 更新信息完毕记录操作日志 ***
            logService.insertSimple(1, 50, objDTO.getId(), 2,
                    "更新配件、采购信息",
                    FastJsonUtils.toJSONString(objDTO),
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 删除&改变状态

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return json
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(HttpServletRequest request, Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = purchaseService.delete(id);

            //删除成功后，将配件/采购明细也一并删除
            if (isNext) {
                TransportPurchaseDetailDTOQuery updateQuery = new TransportPurchaseDetailDTOQuery();
                updateQuery.setDeleteFlag(1);
                updateQuery.setW_partId(id);
                purchaseDetailService.updateInfoByQuery(updateQuery);
            }

            //region *** 更新信息完毕记录操作日志 ***
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            logService.insertSimple(1, 50, id, 4,
                    "删除配件、采购信息",
                    "记录删除：" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    /**
     * 状态改变 ajax异步
     *
     * @param id     记录id
     * @param status 状态
     * @return json
     */
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(HttpServletRequest request, Integer id, Integer status) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            Boolean isNext = purchaseService.changeState(id, status);

            //操作成功后，将配件/采购明细也一并删除
            if (isNext) {
                TransportPurchaseDetailDTOQuery updateQuery = new TransportPurchaseDetailDTOQuery();
                updateQuery.setStopFlag(status);
                updateQuery.setW_partId(id);
                purchaseDetailService.updateInfoByQuery(updateQuery);
            }

            //region *** 更新信息完毕记录操作日志 ***
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            logService.insertSimple(1, 50, id == null ? 0 : id, 2,
                    "更新配件、采购状态",
                    "记录状态更新" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 数据查看

    /**
     * 数据查看
     *
     * @param model     model模型
     * @param id        主键id
     * @param tableName 数据库英文表名
     * @return vm
     */
    @RequestMapping(value = "/show", method = RequestMethod.POST)
    public String show(Model model, Integer id, String tableName) {
        id = (id == null ? 0 : id);

        TransportPurchaseDTO obj = new TransportPurchaseDTO();
        obj.setId(id);

        if (id > 0) {
            obj = purchaseService.getById(id);
        }
        purchaseService.assembleObjInfo(model, tableName, obj);

        return "show/show-template";
    }

    //endregion

    //region 库存盘点

    /**
     * 库存盘点
     *
     * @param model        model
     * @param id           物料ID
     * @param purchaseType 采购类型：1汽车配件 2日常采购
     * @return vm
     */
    @RequestMapping(value = "/inventoryParts", method = RequestMethod.POST)
    public String inventoryParts(Model model, Integer id, Integer purchaseType) {
        id = (id == null ? 0 : id);
        purchaseType = (purchaseType == null ? 0 : purchaseType);

        if (id > 0) {
            TransportPurchaseDTO obj = purchaseService.getById(id);

            if (obj != null) {
                //盘点原则：每个商品、每月盘点一次
                TransportPurchaseInventoryDetailDTOQuery detailDTOQuery = new TransportPurchaseInventoryDetailDTOQuery();
                detailDTOQuery.setPartId(id);
                Calendar calendar = Calendar.getInstance();
                detailDTOQuery.setpYear(calendar.get(Calendar.YEAR));
                detailDTOQuery.setpMonth(calendar.get(Calendar.MONTH) + 1);
                TransportPurchaseInventoryDetailDTO inventoryDetailDTO = inventoryDetailService.getByQuery(detailDTOQuery);
                if (inventoryDetailDTO == null) {
                    inventoryDetailDTO = new TransportPurchaseInventoryDetailDTO();
                    inventoryDetailDTO.setId(0);
                    inventoryDetailDTO.setPurchaseType(purchaseType);
                }
                model.addAttribute("inventoryDetailObj", inventoryDetailDTO);

                //region //是否已经生成盘点单（可以生成多个盘点单）
                //TransportPurchaseInventoryDTOQuery dtoQuery = new TransportPurchaseInventoryDTOQuery();
                //dtoQuery.setPurchaseType(purchaseType);
                //dtoQuery.setpYear(calendar.get(Calendar.YEAR));
                //dtoQuery.setpMonth(calendar.get(Calendar.MONTH) + 1);
                //dtoQuery.setStopFlag(0);
                //TransportPurchaseInventoryDTO inventoryDTO = inventoryService.getByQuery(dtoQuery);
                //if (inventoryDTO == null) {
                //    inventoryDTO = new TransportPurchaseInventoryDTO();
                //    inventoryDTO.setId(0);
                //}
                //model.addAttribute("inventoryObj", inventoryDTO);
                //endregion

                //库存信息
                List<Map<String, String>> rmapList = purchaseDetailService.selectSumCount(id);
                if (rmapList != null) {
                    Map<String, String> rmap = rmapList.get(0);
                    Integer r_counts = GeneralUtils.ObjectToInt(rmap.get("r_counts"));
                    Integer c_counts = GeneralUtils.ObjectToInt(rmap.get("c_counts"));
                    Integer s_counts = GeneralUtils.ObjectToInt(rmap.get("s_counts"));

                    obj.setInCount(r_counts);
                    obj.setOutCount(c_counts);
                    obj.setDamageCount(s_counts);
                    obj.setStockCount(r_counts - c_counts - s_counts);
                }

                model.addAttribute("purchaseObj", obj);
            }
        }

        return "erp/purchase/inventory-modal";
    }

    /**
     * 保存库存盘点
     *
     * @param request           sevlet
     * @param partId            物料Id
     * @param inventoryDetailId 盘点明细Id
     * @param pCount            盘点库存
     * @param exReason          库存异常原因
     * @return json
     */
    @RequestMapping(value = "/saveInventoryParts", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> saveInventoryParts(HttpServletRequest request, Integer purchaseType, Integer partId, Integer inventoryDetailId, Integer pCount, String exReason) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        if (partId == null || partId == 0) {
            map.put("returnMessage", "未查询到盘点物料！");
            return map;
        }

        if (inventoryDetailId == null) {
            inventoryDetailId = 0;
        }

        if (pCount == null) {
            map.put("returnMessage", "物料盘点数量异常！");
            return map;
        }

        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

        if (inventoryDetailId == 0) {
            //新增盘点
            TransportPurchaseInventoryDetailDTO dto = new TransportPurchaseInventoryDetailDTO();
            dto.setPurchaseType(purchaseType);
            dto.setInventoryId(0);
            dto.setPartId(partId);

            //获取//库存信息
            List<Map<String, String>> rmapList = purchaseDetailService.selectSumCount(partId);
            if (rmapList != null) {
                Map<String, String> rmap = rmapList.get(0);
                Integer r_counts = GeneralUtils.ObjectToInt(rmap.get("r_counts"));
                Integer c_counts = GeneralUtils.ObjectToInt(rmap.get("c_counts"));
                Integer s_counts = GeneralUtils.ObjectToInt(rmap.get("s_counts"));

                dto.setrCount(r_counts);
                dto.setcCount(c_counts);
                dto.setsCount(s_counts);
                dto.setCount(r_counts - c_counts - s_counts);

            } else {
                dto.setrCount(0);
                dto.setcCount(0);
                dto.setsCount(0);
                dto.setCount(0);
            }

            dto.setpCount(pCount);
            dto.setProfitLoss(pCount - dto.getCount());

            if (dto.getProfitLoss() < 0) {
                dto.setStatus(-1);
            } else if (dto.getProfitLoss() > 0) {
                dto.setStatus(1);
            } else {
                dto.setStatus(0);
            }

            dto.setExReason(exReason);

            Calendar calendar = Calendar.getInstance();
            dto.setpYear(calendar.get(Calendar.YEAR));
            dto.setpMonth(calendar.get(Calendar.MONTH) + 1);
            dto.setInventory(curr_obj.getId());
            dto.setInventoryDate(new Date());
            dto.setAdminId(curr_obj.getId());
            dto.setCreateTime(new Date());
            dto.setReviewer(0);
            dto.setReviewDate(DateConvertUtils.strToDate("1990-01-01"));
            dto.setStopFlag(0);
            dto.setDeleteFlag(0);
            dto = inventoryDetailService.insert(dto);

            if (dto != null) {
                map.put("returnCode", 1);
                map.put("returnMessage", "物料盘点成功！");
            }

        } else {
            //更新盘点
            TransportPurchaseInventoryDetailDTO orgindto = inventoryDetailService.getById(inventoryDetailId);

            TransportPurchaseInventoryDetailDTO dto = new TransportPurchaseInventoryDetailDTO();
            dto.setId(inventoryDetailId);
            dto.setpCount(pCount);
            dto.setProfitLoss(pCount - orgindto.getCount());
            if (dto.getProfitLoss() < 0) {
                dto.setStatus(-1);
            } else if (dto.getProfitLoss() > 0) {
                dto.setStatus(1);
            } else {
                dto.setStatus(0);
            }
            dto.setExReason(exReason);
            Boolean isNext = inventoryDetailService.updateInfoById(dto);

            //region *** 更新信息完毕记录操作日志 ***
            logService.insertSimple(1, 91, dto.getId(), 2,
                    "更新盘点明细信息",
                    FastJsonUtils.toJSONString(dto),
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            if (isNext) {
                map.put("returnCode", 1);
                map.put("returnMessage", "物料盘点更新成功！");
            }
        }

        return map;
    }
    //endregion

    //region 获取查询列表

    /**
     * 获取查询列表（不带分页）
     *
     * @param model        model
     * @param name         关键词
     * @param purchaseType 1汽车配件 2日常采购
     * @param from         1来自于工单；2来自于勘察；3来自于采购单；4来自于出库单
     * @param pn           页码
     * @param pageSize     分页大小
     * @return vm
     */
    @RequestMapping(value = "/selectParts", method = RequestMethod.POST)
    public String selectParts(Model model, String name, Integer purchaseType, Integer from, Integer pn, Integer pageSize) {

        String templete = "garage/repair-order/parts-select-model";
        if (from == 2) {
            templete = "electric/scenesurvey/parts-select-model";
        }
        if (from == 3) {
            templete = "erp/purchase-doc/parts-select-model";
        }
        if (from == 4) {
            templete = "erp/purchase-out/parts-select-model";
        }

        pn = (pn == null ? 1 : pn);
        pn = (pn <= 0 ? 1 : pn);
        pageSize = (pageSize == null ? 10 : pageSize);
        pageSize = (pageSize <= 0 ? 10 : pageSize);

        TransportPurchaseDTOQuery query = new TransportPurchaseDTOQuery();
        if (StringUtils.isNotBlank(name)) {
            query.setLikeName(name.trim());
        }
        query.setPurchaseType(purchaseType);
        query.setPn(pn);
        query.setPageSize(pageSize);
        query.setStopFlag(0);
        query.setOrderBy("order by id desc");
        Page<TransportPurchaseDTO> choicePage = purchaseService.getForPage(query);
        for (TransportPurchaseDTO item : choicePage.getItems()) {
            item.setCatalogName(modelService.getCatalogName(item.getCatalogId()));
            item.setBrandName(modelService.getCatalogName(item.getBrandId()));
        }

        if (from == 4) {
            List<Map<String, String>> rmapList;
            for (TransportPurchaseDTO item : choicePage.getItems()) {
                //库存信息
                rmapList = purchaseDetailService.selectSumCount(item.getId());
                if (rmapList != null) {
                    Map<String, String> rmap = rmapList.get(0);
                    Integer r_counts = GeneralUtils.ObjectToInt(rmap.get("r_counts"));
                    Integer c_counts = GeneralUtils.ObjectToInt(rmap.get("c_counts"));
                    Integer s_counts = GeneralUtils.ObjectToInt(rmap.get("s_counts"));

                    item.setInCount(r_counts);
                    item.setOutCount(c_counts);
                    item.setDamageCount(s_counts);
                    item.setStockCount(r_counts - c_counts - s_counts);
                }
            }
        }

        model.addAttribute("page", choicePage);

        return templete;
    }

    /**
     * 获取查询列表（带分页）
     *
     * @param name         关键词
     * @param purchaseType 1汽车配件 2日常采购
     * @param from         1来自于工单；2来自于勘察；3来自于采购单；4来自于出库单
     * @param pn           页码
     * @param pageSize     分页大小
     * @return map
     */
    @RequestMapping(value = "/selectPartsPage", method = RequestMethod.POST)
    @ResponseBody
    public Map<Object, Object> selectPartsPage(String name, Integer purchaseType, Integer from, Integer pn, Integer pageSize) {
        pn = (pn == null || pn <= 0) ? 1 : pn;
        pageSize = (pageSize == null || pageSize <= 0) ? 5 : pageSize;

        Map<Object, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("pn", pn);
        map.put("pageSize", pageSize);

        TransportPurchaseDTOQuery query = new TransportPurchaseDTOQuery();
        if (StringUtils.isNotBlank(name)) {
            query.setLikeName(name.trim());
        }
        query.setPurchaseType(purchaseType);
        query.setPn(pn);
        query.setPageSize(pageSize);
        query.setStopFlag(0);
        query.setOrderBy("order by id desc");
        Page<TransportPurchaseDTO> dataPage = purchaseService.getForPage(query);
        for (TransportPurchaseDTO item : dataPage.getItems()) {
            item.setCatalogName(modelService.getCatalogName(item.getCatalogId()));
            item.setBrandName(modelService.getCatalogName(item.getBrandId()));
            item.setProductTypeName(ProductTypeEnum.getEnumByKey(item.getProductType()));
        }

        if (from == 3 || from == 4) {
            List<Map<String, String>> rmapList;
            for (TransportPurchaseDTO item : dataPage.getItems()) {
                //库存信息
                rmapList = purchaseDetailService.selectSumCount(item.getId());
                if (rmapList != null) {
                    Map<String, String> rmap = rmapList.get(0);
                    Integer r_counts = GeneralUtils.ObjectToInt(rmap.get("r_counts"));
                    Integer c_counts = GeneralUtils.ObjectToInt(rmap.get("c_counts"));
                    Integer s_counts = GeneralUtils.ObjectToInt(rmap.get("s_counts"));

                    item.setInCount(r_counts);
                    item.setOutCount(c_counts);
                    item.setDamageCount(s_counts);
                    item.setStockCount(r_counts - c_counts - s_counts);
                }
            }
        }

        map.put("partsAjaxPage", dataPage);
        map.put("partsAjaxPagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));

        return map;
    }
    //endregion

    //region 获取查询信息
    @RequestMapping(value = "/getPartInfo", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getPartInfo(Integer partId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        if (partId == null || partId <= 0) {
            return map;
        }

        TransportPurchaseDTO dto = purchaseService.getById(partId);
        if (dto != null) {
            map.put("partName", dto.getPartName());
            map.put("specialName", dto.getSpecialName() == null ? "" : dto.getSpecialName());
            map.put("modalName", dto.getModalName() == null ? "" : dto.getModalName());
            map.put("price", 0);

            TransportPurchaseDetailDTOQuery query = new TransportPurchaseDetailDTOQuery();
            query.setPartId(partId);
            query.setOpType(1);
            query.setrPurchaseType(1);
            query.setOrderBy("order by id desc");
            TransportPurchaseDetailDTO detailDTO = purchaseDetailService.getByQuery(query);
            if (detailDTO != null) {
                map.put("price", detailDTO.getrPrice());
            }

            map.put("returnCode", 1);
        }

        return map;
    }
    //endregion
}